<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
             v-show="showSearch" label-width="68px">
      <el-row>
        <el-form-item label="服务类型" prop="typeId">
          <el-select v-model="queryParams.typeId"
                     @change="handleServTypeChange"
                     placeholder="请选择服务类型">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="servType in serviceTypeAndItemOptions"
              :key="servType.id"
              :label="servType.name"
              :value="servType.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="服务项目" prop="serviceItemId">
          <el-select v-model="queryParams.serviceItemId" placeholder="请选择服务项目">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="servItem in serviceItemOption"
              :key="servItem.id"
              :label="servItem.itemName"
              :value="servItem.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="服务项目名称" prop="itemName" label-width="auto">
          <el-input
            v-model="queryParams.itemName"
            placeholder="请输入搜索关键词"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="所在区域" prop="region1Id">
          <el-select v-model="queryParams.region1Id" clearable
                     @change="handleRegion1Change"
                     placeholder="请选择区域">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="region1 in regionTree"
              :key="region1.id"
              :label="region1.name"
              :value="region1.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在街道" prop="region2Id">
          <el-select v-model="queryParams.region2Id" clearable
                     placeholder="请选择街道">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="region2 in region2List"
              :key="region2.id"
              :label="region2.name"
              :value="region2.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="员工数" prop="staffNum" label-width="auto">
            <el-radio-group v-model="queryParams.staffNum"
                            @input="queryStaffNumChange"
                            size="mini">
              <el-radio-button label="" border>全部</el-radio-button>
              <el-radio-button label="low" border>5人以内</el-radio-button>
              <el-radio-button label="mid" border>6-20人</el-radio-button>
              <el-radio-button label="high" border>20人以上</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="服务商年限" prop="since" label-width="auto">
            <el-radio-group v-model="queryParams.since"
                            @input="querySinceChange"
                            size="mini">
              <el-radio-button label="" border>全部</el-radio-button>
              <el-radio-button label="low" border>1年以内</el-radio-button>
              <el-radio-button label="mid" border>1-3年</el-radio-button>
              <el-radio-button label="high" border>3年以上</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['health:healthBmService:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['health:healthBmService:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['health:healthBmService:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="healthBmServiceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="服务id" align="center" width="60" prop="id"/>
      <el-table-column label="服务项目" align="center" width="90" prop="serviceItemId">
        <template slot-scope="scope">
          {{ serviceItemName(scope.row.serviceItemId) }}
        </template>
      </el-table-column>
      <el-table-column label="服务商" align="center" prop="supplierId">
        <template slot-scope="scope">
          {{ supplierName(scope.row.supplierId) }}
        </template>
      </el-table-column>
      <el-table-column label="服务价格" align="center" prop="priceMin">
        <template slot-scope="scope">
          {{ `${scope.row.priceMin}~${scope.row.priceMax}元` }}
        </template>
      </el-table-column>
      <el-table-column label="计费单位" align="center" width="80" prop="unit"/>
      <el-table-column label="封面图" align="center" prop="cover">
        <template slot-scope="scope">
          <image-preview :src="scope.row.cover" :width="48" :height="48"/>
        </template>
      </el-table-column>
      <el-table-column label="服务简介" align="center" prop="brief">
        <!--文字太长，只保留两行，多余的显示省略号-->
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.brief" placement="top">
            <div style="
                overflow: hidden;
                display: -webkit-box;
                text-overflow: ellipsis;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                white-space: normal;
              ">
              {{ scope.row.brief }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="tel"/>
      <el-table-column label="联系人" align="center" prop="contact"/>
      <el-table-column label="地址" align="center" prop="address">
        <!--文字太长，只保留两行，多余的显示省略号-->
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.address" placement="top">
            <div style="
                overflow: hidden;
                display: -webkit-box;
                text-overflow: ellipsis;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                white-space: normal;
              ">
              {{ scope.row.address }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['health:healthBmService:edit']"
            >修改
            </el-button>
          </el-row>
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['health:healthBmService:remove']"
            >删除
            </el-button>
          </el-row>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改便民服务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="服务项目" prop="serviceItemId">
              <template slot-scope="scope">
                <el-cascader
                  placeholder="试试搜索项目名称"
                  v-model="form.serviceItemId"
                  :options="serviceTypeAndItemOptions"
                  :props="{ value: 'id',label: 'name',expandTrigger: 'hover',emitPath:false}"
                  filterable>
                </el-cascader>
              </template>
            </el-form-item>

            <el-form-item label="服务商" prop="supplierId">
              <el-select
                v-model="form.supplierId"
                filterable
                remote
                reserve-keyword
                clearable
                placeholder="请输入服务商名称"
                :remote-method="remoteSearchSupplier"
                :loading="loading">
                <el-option
                  v-for="suppItem in supplierOptions"
                  :key="suppItem.id"
                  :label="suppItem.name"
                  :value="suppItem.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="计费方式" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择计费方式">
                <el-option
                  v-for="unit in feeUnits"
                  :key="unit.id"
                  :label="unit.name"
                  :value="unit.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面图片" prop="cover">
              <image-upload v-model="form.cover"
                            :limit="1"
                            :isShowTip="false"
              />
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="服务价格">
          <el-row>
            <el-col :span="6">
              <el-form-item label="" prop="priceMin">
                <el-input v-model="form.priceMin" clearable placeholder="最低价"/>
              </el-form-item>
            </el-col>
            <el-col :span="2" align="center">
              <span>~</span>
            </el-col>
            <el-col :span="6">
              <el-form-item label="" prop="priceMax">
                <el-input v-model="form.priceMax" clearable placeholder="最高价"/>
              </el-form-item>
            </el-col>
            <el-col :span="2" align="center">
              <span>（元）</span>
            </el-col>
          </el-row>
        </el-form-item>


        <el-form-item label="服务简介" prop="brief">
          <el-input v-model="form.brief" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入服务联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="联系电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入服务电话"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="text" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="服务区域" prop="serviceRegion">
          <!--<el-input v-model="form.serviceRegion" placeholder="请输入"/>-->
          <el-cascader
            v-model="form.serviceRegion"
            :options="regionTree"
            clearable
            :props="{ value: 'id',label: 'name', emitPath:true,
                      expandTrigger: 'hover',multiple: true}"
            :style="{width:'100%'}"
          ></el-cascader>
          <!--  使el-cascader 支持选择任意一级 checkStrictly: true   -->
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listHealthBmService,
  getHealthBmService,
  delHealthBmService,
  addHealthBmService,
  updateHealthBmService
} from "@/api/health/healthBmService";
import {listHealthServiceType} from "@/api/health/healthServiceType";
import {listHealthSupplier} from "@/api/health/healthSupplier";
import {getHealthRegionTree, listHealthRegion} from "@/api/health/healthRegion";
import {listHealthServiceItem} from "@/api/health/healthServiceItem";

export default {
  name: "HealthBmService",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 带9个查询参数
        itemName: '',
        staffNumMin: 0,
        staffNumMax: 99999,
        sinceMin: 0,
        sinceMax: 9999,
        serviceItemId: '',
        typeId: '',      //有serviceItemId时，typeId失效
        region1Id: '',
        region2Id: ''
      },
      // 便民服务表格数据
      healthBmServiceList: [],
      // 全部的服务提供商列表
      supplierList: [],
      // 搜索的服务提供商列表
      supplierOptions: [],
      // 区域树(一二三级)
      regionTree: [],
      // 区域列表（一二三级）
      regionList: [],
      // 二级区域列表
      region2List: [],
      // 服务单位
      serviceUnits: [
        "次",
        "小时",
        "天",
        "星期",
        "月",
        "年"
      ],
      //服务类型和服务项目列表（二级树结构）
      serviceTypeAndItemOptions: [],
      // 全部的服务项目
      serviceItemList: [],
      // 查询条件中的“服务项目”
      serviceItemOption: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serviceItemId: [
          {required: true, message: "服务项目id不能为空", trigger: "blur"}
        ],
        supplierId: [
          {required: true, message: "服务商ID不能为空", trigger: "blur"}
        ],
        priceMin: [
          {required: true, message: "服务价格低限不能为空", trigger: "blur"}
        ],
        priceMax: [
          {required: true, message: "服务价格高限不能为空", trigger: "blur"}
        ],
        unit: [
          {required: true, message: "服务单位不能为空", trigger: "blur"}
        ],
        cover: [
          {required: true, message: "服务封面图不能为空", trigger: "blur"}
        ],
        tel: [
          {required: true, message: "服务电话不能为空", trigger: "blur"}
        ],
        contact: [
          {required: true, message: "服务联系人不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "服务地址不能为空", trigger: "blur"}
        ],
        serviceRegion: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
      }
    };
  },
  computed: {
    feeUnits() {
      return this.serviceUnits.map(u => {
        return {name: `${u}`, id: `${u}`}
      })
    },
    //利用闭包，实现计算属性中返回一个函数（计算属性传参）
    serviceItemName() {
      return function (id) {
        let itemName = 'null'
        for (let i = 0; i < this.serviceItemList.length; i++) {
          if (this.serviceItemList[i].id === id) {
            itemName = this.serviceItemList[i].itemName
            break
          }
        }
        return itemName;
      }
    },
    //利用闭包，实现计算属性中返回一个函数（计算属性传参）
    supplierName() {
      return function (id) {
        let supName = 'null'
        for (let i = 0; i < this.supplierList.length; i++) {
          if (this.supplierList[i].id === id) {
            supName = this.supplierList[i].name
            break;
          }
        }
        return supName;
      }
    }
  },
  created() {
    this.getRegionTree();
    this.getRegionList();
    this.getSupplierList();
    this.getHealthServiceItem();
    this.getServiceTypeAndItemList();
    this.getList();
  },
  methods: {
    remoteSearchSupplier(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.supplierOptions = this.supplierList.filter(item => {
            //通过name进行搜索匹配
            return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.supplierOptions = [];
      }
    },
    // 查询1、2、3级区域列表
    getRegionList() {
      listHealthRegion().then(resp => {
        this.regionList = resp.data
        //初始化二级区域
        this.handleRegion1Change();
      })
    },
    //查询：供应商列表
    getSupplierList() {
      listHealthSupplier().then(resp => {
        this.supplierList = resp.rows;
      })
    },
    //查询： 所有区域树
    getRegionTree() {
      getHealthRegionTree().then(resp => {
        this.regionTree = this.deleteEmptyChildren(resp.data);
      })
    },
    //查询：服务类型、服务项目的列表
    getServiceTypeAndItemList() {
      listHealthServiceType().then(resp => {
        this.serviceTypeAndItemOptions = resp.rows;
        //调整cascade所需格式
        this.serviceTypeAndItemOptions.map(typ => {
          this.mapServiceTypeAndItemTree(typ)
        })
      })
    },
    getHealthServiceItem() {
      listHealthServiceItem().then(resp => {
        this.serviceItemList = resp.rows;
        //将 全部服务项目 添加到查询栏中 服务项目 下拉框
        this.serviceItemOption = this.serviceItemList
      })
    },
    /** 查询便民服务列表 */
    getList() {
      this.loading = true;
      listHealthBmService(this.queryParams).then(response => {
        this.healthBmServiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    mapServiceTypeAndItemTree(typ) {
      //判断 type下面是否有 item
      const haveServiceItems = Array.isArray(typ.serviceItemList) && typ.serviceItemList.length > 0;
      if (haveServiceItems) {
        typ.children = typ.serviceItemList.map(item => {
          item.name = item.itemName
          item.type = typ.id
          return item;
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serviceItemId: null,
        supplierId: null,
        priceMin: null,
        priceMax: null,
        unit: null,
        cover: null,
        brief: null,
        tel: null,
        contact: null,
        address: null,
        serviceRegion: [],
        createBy: null,
        createTime: null
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      //展示供应商
      this.supplierOptions = this.supplierList
      this.open = true;
      this.title = "添加便民服务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHealthBmService(id).then(response => {
        this.form = response.data;
        //处理数据格式：form.serviceRegion原始格式是【“字符串以逗号连接”】，处理为 【二维数组】
        // '6:7:8,6:7:9'  ==>  [[6,7,8],[6,7,9]]
        let region1dArr = this.form.serviceRegion.split(',')
        this.form.serviceRegion = []
        region1dArr.forEach( arrItem => {
          let oneRegionArray = arrItem.split(':')
          this.form.serviceRegion.push(oneRegionArray);
        })
        //展示供应商
        this.supplierOptions = this.supplierList
        this.open = true;
        this.title = "修改便民服务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //处理数据格式：form.serviceRegion原始格式是【二维】数组，处理为 “字符串以逗号连接”
          //原始格式是二维数组： [[6,7,8],[6,7,9]]
          let region2dArr = this.form.serviceRegion.map(arrItem => {
            return arrItem.join(':')
          })
          // 用上面代码处理后是一维数组: ['6:7:8','6:7:9']
          // 继续处理为字符串 ： '6:7:8,6:7:9'
          let region1dArr = region2dArr.join(',')
          this.form.serviceRegion = region1dArr
          // 判断是新增？ 还是修改？
          if (this.form.id != null) {
            updateHealthBmService(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHealthBmService(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除便民服务编号为"' + ids + '"的数据项？').then(function () {
        return delHealthBmService(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 去除tree中 空 children
    deleteEmptyChildren(arr) {
      for (let i = arr.length; i--; i > 0) {
        if (arr[i].children && arr[i].children.length > 0) {
          this.deleteEmptyChildren(arr[i].children)
        } else {
          delete arr[i].children
        }
      }
      return arr
    },
    //查询条件中服务项目改变
    handleServTypeChange(servTyp1Id) {
      if (servTyp1Id == null || servTyp1Id == '') {
        //给 服务项目 下拉中，填充全部的“服务项目”
        this.serviceItemOption = this.serviceItemList
        //重置二级区域
        // this.region2List.map(item => {
        //   item.label = item.name;
        //   item.value = item.id
        // })
        //默认选中二级的“全部”
        this.queryParams.serviceItemId = ''
      } else {
        let currentServItems = this.serviceTypeAndItemOptions.find((servTyp) => {
          return servTyp.id === servTyp1Id;
        })
        // console.log(currentServItems)
        this.serviceItemOption = currentServItems.serviceItemList;
      }
    },
    //查询条件中，一级区域改变，联动修改二级区域
    handleRegion1Change(r1Id) {
      if (r1Id == null || r1Id == '' || r1Id == undefined) {
        //给二级区域下拉中，填充全部的“二级区域”
        this.region2List = this.regionList.filter(item => {
          return item.level == 2
        })
        //选中二级“全部”
        this.queryParams.region2Id = ''
      } else {
        let currentRegion1 = this.regionTree.find((item) => {
          return item.id === r1Id;
        })
        this.region2List = currentRegion1.children;
      }
    },
    // 查询条件：员工数 改变
    queryStaffNumChange(val){
      console.log(val)
      switch (val){
        case 'low':
          this.queryParams.staffNumMin = 0;
          this.queryParams.staffNumMax = 6;
          break;
        case 'mid':
          this.queryParams.staffNumMin = 6;
          this.queryParams.staffNumMax = 21;
          break;
        case 'high':
          this.queryParams.staffNumMin = 21;
          this.queryParams.staffNumMax = 999999;
          break;
        default:
          this.queryParams.staffNumMin = null;
          this.queryParams.staffNumMax = null;
      }
      console.log(this.queryParams)
      this.getList();
    },
    // 查询条件：营业年限 改变
    querySinceChange(val){
      console.log(val)
      switch (val){
        case 'low':
          this.queryParams.sinceMin = 0;
          this.queryParams.sinceMax = 1;
          break;
        case 'mid':
          this.queryParams.sinceMin = 1;
          this.queryParams.sinceMax = 4;
          break;
        case 'high':
          this.queryParams.sinceMin = 4;
          this.queryParams.sinceMax = 999;
          break;
        default:
          this.queryParams.sinceMin = null;
          this.queryParams.sinceMax = null;
      }
      this.getList();
    }
  }
}
</script>
